package com.example.api2interface.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.SortedMap;
import java.util.TreeMap;

public class HttpDataUtil {
    /**
     * post请求处理：获取body参数，转换为SortedMap
     */
    public static SortedMap<String, String> getBodyParams(HttpServletRequest request) throws IOException {
        byte[] requestBody = StreamUtils.copyToByteArray(request.getInputStream());
        String body = new String(requestBody);

        /*
         解析成一个SortedMap，好处：在后续处理参数，
         可以保证参数顺序一致，避免因为 JSON 原本的顺序不固定而导致结果不同。
         */
        // 方式1，需要高版本jdk
        // TreeMap<String, String> map = JSON.parseObject(body, new TypeReference<TreeMap<String, String>>() {});
        // 方式2
        SortedMap<String, String> map = JSON.parseObject(body, SortedMap.class);
        return map;
    }

    /**
     * get请求处理：将URL请求参数转换成SortedMap
     */
    public static SortedMap<String, String> getUrlParams(HttpServletRequest request) {
        String param = "";
        SortedMap<String, String> result = new TreeMap<>();

        // 返回？后面的原始查询字符串
        if (StringUtils.isEmpty(request.getQueryString())) {
            return result;
        }

        // url解码：
        try {
            param = URLDecoder.decode(request.getQueryString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String[] split = param.split("&");
        for (String s : split) {
            String[] paramsList = s.split("=");
            result.put(paramsList[0],paramsList[1]);
        }
        return result;
    }
}
